package com.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class Anquan
 */

public class MyFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public MyFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	//private boolean OK = true;
	private static final String[] warnstrs = new String[] { "<script>","<script/>" };

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		((HttpServletRequest) request).getSession(false);
		((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", "*");
		((HttpServletResponse) response).setHeader("Access-Control-Allow-Headers", "Content-Type,token"); // 加入支持自定义的header
		((HttpServletResponse) response).setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
		// ((HttpServletResponse) response).setHeader("Content-Type",
		// "application/json;charset=utf-8");

		HttpServletResponse servletresponse = (HttpServletResponse) response;
		//String ct = request.getContentType();
		//System.out.println("过滤器:"+ct);
		boolean status = false;
		//if (ct!=null && (ct.indexOf("text") > -1 || ct.indexOf("html") > -1)  ) {
			java.util.Enumeration<String> params = request.getParameterNames();
			String param = "";
			String paramValue = "";
			while (params.hasMoreElements()) {
				param = (String) params.nextElement();
				String[] values = request.getParameterValues(param);
				paramValue = "";
				for (int i = 0; i < values.length; i++)
					paramValue = paramValue + values[i];
				for (int i = 0; i < warnstrs.length; i++)
					if (paramValue.indexOf(warnstrs[i]) >= 0) {
						status = true;
						break;
					}
				if (status) {
					System.out.println("已拦截");
					PrintWriter out = servletresponse.getWriter();
					out.print("<script language='javascript'>alert(\"对不起！您输入内容含有非法字符。如：\\\"'\\\".等\");"
							// + servletrequest.getRequestURL()
							+ "window.history.go(-1);</script>");
					return;
				}
			}
		//}
//
		chain.doFilter(request, response);

	}

	// ((HttpServletResponse ) response).setHeader("X-Powered-By"," 3.2.1");
	// response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,token");
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

}
